package cn.hdu.liang.ch3;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;

public class Lambdas {
    public static void main(String[] args) {
        List<String> listOfString = new ArrayList<>(Arrays.asList("aaa", "bbb", "ccc", "ddd", "eee"));
        System.out.println(listOfString);

        Predicate<String> nonEmptyStringPredicate = (String s) -> !s.isEmpty();
        List<String> nonEmpty = filter(listOfString, nonEmptyStringPredicate);
        System.out.println(nonEmpty);

        forEach(listOfString, System.out::println);

        List<Integer> list = map(listOfString, String::length);
        System.out.println(list);

        List<String> str = Arrays.asList("a", "b", "A", "B");
        str.sort(String::compareToIgnoreCase);
    }

    public static <T, R> List<R> map(List<T> list, Function<T, R> f) {
        List<R> result = new ArrayList<R>();
        for(T s : list) {
            result.add(f.apply(s));
        }
        return result;
    }

    public static <T> void forEach(List<T> list, Consumer<T> c) {
        for(T i : list) {
            c.accept(i);
        }
    }

    public static <T> List<T> filter(List<T> list, Predicate<T> p) {
        List<T> results = new ArrayList<T>();
        for(T s : list) {
            if(p.test(s)) {
                results.add(s);
            }
        }
        return results;
    }
}
